package sqrlx

import (
	sq "github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/logx"
)

type InSubquery struct {
	Column string
	Query  sq.Sqlizer
	Neg    bool
}

func (in InSubquery) ToSql() (string, []interface{}, error) {
	sql, args, err := in.Query.ToSql()
	if err != nil {
		return "", nil, err
	}

	sql = " IN (" + sql + ")"
	if in.Neg {
		sql = " NOT" + sql
	}

	return in.Column + sql, args, nil
}

func UniqueInt64(ids []int64) (res []int64) {
	logx.Infof("UniqueInt64 ids : %+v ", ids)
	res = ids[:]
	idx := len(res) - 1
	for ; idx > 0; idx -= 1 {
		if res[idx] <= 0 { // 小于等于0的去除
			res = append(res[:idx], res[idx + 1:]...)
			break
		}

		for pidx := idx - 1; pidx >= 0; pidx -= 1 {
			if res[pidx] == res[idx] { // 重复的去除
				res = append(res[:idx], res[idx + 1:]...)
				break
			}
		}
	}
	// logx.Errorf("Payment successful send wechat mini subscription message failed retryNum ： %d , err:%v, msg ： %+v ", retryNum, err, msg)
	// logx.Error("PaymentUpdateStatusMq->Consume Unmarshal err : %v , val : %s", err, val)
	logx.Infof("UniqueInt64 res : %+v ", res)
	return
}

func UniqueString(names []string) (res []string) {
	res = names[:]
	idx := len(res) - 1
	for ; idx > 0; idx -= 1 {
		if res[idx] == "" {
			res = append(res[:idx], res[idx + 1:]...)
			break
		}

		for pidx := idx - 1; pidx > 0; pidx -= 1 {
			if res[pidx] == res[idx] {
				res = append(res[:idx], res[idx + 1:]...)
				break
			}
		}
	}
	return
}

func Dedupe(ids []int64) (deduped []int64, idMap map[int64][]int) { ////
	idMap = make(map[int64][]int)
	for i, id := range ids {
		if _, ok := idMap[id]; !ok {
			deduped = append(deduped, id)
		}

		idMap[id] = append(idMap[id], i)
	}

	return
}
